<template>
  <div class="yun-code" ref="codeView" v-bind="$attrs">
    <codemirror
    v-model="code"
    placeholder="请输入..."
    style="height: 100%"
    :autofocus="true"
    :indent-with-tab="true"
    :tab-size="2"
    :extensions="extensions"
    @ready="handleReady"
    @blur="codeBlurToView"
  />
  <!-- @change="console.log('change', $event)"
    @focus="console.log('focus', $event)"
    @blur="console.log('blur', $event)" -->
  </div>
</template>
<script setup>
import {ref,shallowRef,defineProps, watch} from "vue"
import { Codemirror } from 'vue-codemirror'
import {  html } from "@codemirror/lang-html";
import {  vue } from "@codemirror/lang-vue";
import {css} from "@codemirror/lang-css";
import { oneDark } from '@codemirror/theme-one-dark'
const emit = defineEmits(['codeToView'])
const extensions = [html(),vue(),css(), oneDark]
const view = shallowRef()
const handleReady = (payload) => {
  view.value = payload.view
}

// const getCodemirrorStates = () => {
//     const state = view.value.state
//     const ranges = state.selection.ranges
//     const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
//     const cursor = ranges[0].anchor
//     const length = state.doc.length
//     const lines = state.doc.lines
// }
const code = ref('')
const props = defineProps({
  code:String
})
watch(()=>props.code,()=>{
  code.value = props.code
},{
  immediate: true
})
const codeBlurToView = ()=>{
  emit("codeToView")
}
const getCode = ()=>{
  return code.value
}
const resetCode = ()=>{
  code.value = props.code
}
defineExpose({
  getCode,
  resetCode
})
</script>
<style lang="scss" scoped>
.yun-code{
  height:100%;
}
</style>